package com.iflytek.jzcpx.procuracy.tools.common;

import java.io.File;
import java.io.IOException;

import cn.hutool.core.util.IdUtil;
import org.apache.commons.lang3.StringUtils;

/**
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2022/4/30
 */
public class FileUtils {

    /**
     * 获取系统临时目录
     *
     * @return
     */
    public static String getTmpDir() throws RuntimeException {
        String tmpDir = System.getProperty("java.io.tmpdir");
        if (StringUtils.isBlank(tmpDir)) {
            tmpDir = "/tmp";
        }
        File tmpFolder = new File(tmpDir);
        if (!tmpFolder.exists()) {
            try {
                org.apache.commons.io.FileUtils.forceMkdir(tmpFolder);
            }
            catch (IOException e) {
                throw new RuntimeException("创建临时目录失败", e);
            }
        }
        return tmpDir;
    }

    public static File writeTmpFile(byte[] fileBytes, String filename) throws IOException {
        String tmpDir = getTmpDir();
        tmpDir = StringUtils.appendIfMissing(tmpDir, File.separator);
        filename = tmpDir + IdUtil.objectId() + filename;
        File file = new File(filename);
        org.apache.commons.io.FileUtils.writeByteArrayToFile(file, fileBytes);
        return file;
    }

    public static boolean deleteQuietly(File videoFile) {
        if (videoFile == null || !videoFile.exists()) {
            return true;
        }

        return org.apache.commons.io.FileUtils.deleteQuietly(videoFile);
    }
}
